const portfinder = require('portfinder')
const fs = require('fs')
const chalk = require('chalk')
const os = require("os")
const spawn = require('child_process').spawn
const path = require("path")
/**
 * 获取可用端口
 * @param {*} port 最小端口 
 * @param {*} stopPort 最大端口
 * @returns 
 */
function getPort(port, stopPort) {
  port = port || 8000
  stopPort = stopPort || 65535
  return portfinder.getPortPromise({ port, stopPort })
}


/**
 * 报错提示
 * @param {*} msg 
 */
function error(msg) {
  console.log(chalk.red(msg))
}


/**
 * 调用本地bin 命令
 * @param {*} cliName 
 * @param {*} args 
 * @returns 
 */
function getShellCmd(cliName, args,options) {
  const osCMD = os.platform() === 'win32' ? '.cmd' : ''
  let cmd = path.resolve(__dirname,'../node_modules/.bin/' + cliName + osCMD)
  return spawn(cmd, args,options)
}

/**
 * 判断路径是否为文件夹
 * @param {*} fPath 
 * @returns 
 */
function isDirectory(fPath) {
  try {
    const stat = fs.lstatSync(fPath);
    return stat.isDirectory();
  }catch(err){
     return false;
  }
}

/**
 * 判断路径是否为文件
 * @param {*} fPath 
 * @returns 
 */
function isFile(fPath) {
  try {
    const stat = fs.lstatSync(fPath);
    return stat.isFile();
  }catch(err){
     return false;
  }
}

module.exports = {
  getPort,
  error,
  getShellCmd,
  isDirectory,
  isFile
}
